package com.ruibang.glass.produce.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.produce.constant.Constants;
import com.ruibang.glass.produce.domain.req.CommonTrendChartReq;
import com.ruibang.glass.produce.domain.req.UniformityMixtureReq;
import com.ruibang.glass.produce.domain.resp.UniformityMixtureTrendChart;
import com.ruibang.glass.produce.entity.UniformityMixture;
import com.ruibang.glass.produce.mapper.UniformityMixtureMapper;
import com.ruibang.glass.produce.service.UniformityMixtureService;
import com.ruibang.glass.produce.util.ExcelStyleUtils;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 生产-理化-混合料均匀度表 服务实现类
 * </p>
 *
 * @author songJinKang
 * @since 2024-03-12
 */
@Slf4j
@Service
public class UniformityMixtureServiceImpl extends ServiceImpl<UniformityMixtureMapper, UniformityMixture> implements UniformityMixtureService {
    @Autowired
    private RedisSingleService redisService;

    @Override
    public IPage<UniformityMixture> pageQuery(UniformityMixtureReq uniformityMixtureReq) {
        QueryWrapper<UniformityMixture> qw = new QueryWrapper<>();
        qw.lambda().eq(UniformityMixture::getIsDelete, Constants.ZERO_STR);
        if (uniformityMixtureReq.getStartTime() != null && uniformityMixtureReq.getEndTime() != null) {
            qw.lambda().ge(UniformityMixture::getCheckTime, uniformityMixtureReq.getStartTime());
            qw.lambda().le(UniformityMixture::getCheckTime, uniformityMixtureReq.getEndTime());
        }
        qw.lambda().orderByDesc(UniformityMixture::getCreateTime);
        return this.page(new Page<>(uniformityMixtureReq.getPageNo(), uniformityMixtureReq.getPageSize()), qw.lambda());
    }

    @Override
    public void delete(String id) {
        lambdaUpdate().eq(UniformityMixture::getId, id).set(UniformityMixture::getIsDelete, Constants.ONE_STR).update();
    }

    @Override
    public UniformityMixtureTrendChart trendChart(CommonTrendChartReq trendChartReq) {
        //默认查询3天
        if (trendChartReq.getStartTime() == null || trendChartReq.getEndTime() == null) {
            LocalDateTime now = LocalDateTime.now();
            trendChartReq.setStartTime(now.minusDays(3));
            trendChartReq.setEndTime(now);
        }
        //组合数据
        UniformityMixtureTrendChart uniformityMixtureTrendChart = new UniformityMixtureTrendChart();
        List<UniformityMixture> data = baseMapper.trendChart(trendChartReq);
        if (CollectionUtils.isNotEmpty(data)) {
            uniformityMixtureTrendChart.setF2(data.stream().map(UniformityMixture::getF2).collect(Collectors.toList()));
            uniformityMixtureTrendChart.setCollectTime(data.stream().map(e -> e.getCheckTime().format(Constants.DATE_TIME_FORMATTER)).collect(Collectors.toList()));
            uniformityMixtureTrendChart.setData(data);
        }
        return uniformityMixtureTrendChart;
    }

    @Override
    public void export(UniformityMixtureReq uniformityMixtureReq, HttpServletResponse response) {
        uniformityMixtureReq.setPageNo(-1);
        uniformityMixtureReq.setPageSize(-1);
        IPage<UniformityMixture> page = this.pageQuery(uniformityMixtureReq);
        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            List<UniformityMixture> uniformityMixtureList = page.getRecords();
            try {
                EasyExcel.write(response.getOutputStream(), UniformityMixture.class)
                        .registerWriteHandler(ExcelStyleUtils.createTableStyle())
                        .sheet("history_data").doWrite(uniformityMixtureList);
            } catch (IOException e) {
                log.error("数据导出失败：{}", e.getMessage());
            }
        }
    }

    @Override
    public void saveInfo(UniformityMixture uniformityMixture) {
        uniformityMixture.setIsDelete(Constants.ZERO_STR);
        setUserName(uniformityMixture);
        this.save(uniformityMixture);
    }

    @Override
    public void edit(UniformityMixture uniformityMixture) {
        setUserName(uniformityMixture);
        this.updateById(uniformityMixture);
    }

    private void setUserName(UniformityMixture uniformityMixture) {
        String checkById = uniformityMixture.getCheckById();
        String createUserId = uniformityMixture.getCreateUserId();
        if (StringUtils.isNotBlank(checkById)) {
            Object userObj = redisService.hget(RedisKey.USER_GROUP_TYPE, checkById);
            if (userObj != null && StringUtils.isNotBlank(userObj.toString())) {
                uniformityMixture.setCheckBy(userObj.toString());
            }
        } else {
            uniformityMixture.setCheckBy("");
        }
        if (StringUtils.isNotBlank(createUserId)) {
            Object userObj = redisService.hget(RedisKey.USER_GROUP_TYPE, createUserId);
            if (userObj != null && StringUtils.isNotBlank(userObj.toString())) {
                uniformityMixture.setCreateUserName(userObj.toString());
            }
        } else {
            uniformityMixture.setCreateUserName("");
        }
    }
}
